import { authKey } from '@/config/authKey'

/**
 * 格式化 authKey 的 code
 *
 * @export
 * @param {*} authKeyList
 * @param {boolean} [status=false]
 * @returns
 */
export function formatMenusCode(authKeyList, status = false) {
  const authList = JSON.parse(JSON.stringify(authKeyList))
  const mapAuthList = (list, obj = {}) => {
    list.map(menu => {
      menu.status = status
      obj.code && (menu.code = obj.code + '_' + menu.code)
      menu.children && mapAuthList(menu.children, menu)
    })
  }
  mapAuthList(authList)
  return authList
}

/**
 * 获取有权限的菜单的 path
 *
 * @export
 * @param {*} menus
 * @param {*} rightStr
 * @returns
 */
export function getPathListByMenus(authKeyList, rightStr) {
  const pathList = []
  if (!rightStr) return pathList
  const rightList = rightStr.split(',')
  const getPath = (list) => {
    list.map(item => {
      if (rightList.includes(item.code)) {
        item.path && pathList.push(item.path)
      }
      if (item.children && item.children.length) getPath(item.children)
    })
  }
  getPath(authKeyList)
  return pathList
}

/**
 * 获取 Menus
 *
 * @export
 * @param {*} routes
 * @param {*} pathList
 * @returns
 */
export function getMenusByPath(routes, pathList) {
  const newRoutes = routes.filter(route => {
    const routeChild = route.children
    if (routeChild && routeChild.length && !routeChild[0].type) {
      route.children = routeChild.filter(item => pathList.includes(item.path))
    }
    return pathList.includes(route.path)
  })
  return newRoutes
}

export function formatMenus(routes, rightStr) {
  const authKeyList = formatMenusCode(authKey)
  const pathList = getPathListByMenus(authKeyList, rightStr)
  const newRoutes = getMenusByPath(routes, pathList)
  return newRoutes
}
